require('page/common/header/index.js')

var _order_service = require('service/order-service.js');

var confirmOrder = {
    init: function () {
        this.bindEvents();
        this.loadOrderDetails();
        return this;
    },

    bindEvents: function () {
        var that = this;
        $('#confirmed').on('click', function (e) {
            e.preventDefault();
            that.submitOrder();
        });
    },

    loadOrderDetails: function () {
        // 从 localStorage 获取订单数据
        const orderData = JSON.parse(localStorage.getItem('pendingOrder'));
        
        if (!orderData) {
            alert('没有找到订单数据！');
            window.location.href = './order-orderForm.html';
            return;
        }

        // 填充订单信息到页面
        $("#creditcard").text(orderData.creditcard);
        $("#exprdate").text(orderData.exprdate);
        $("#billtofirstname").text(orderData.billTo.firstName);
        $("#billtolastname").text(orderData.billTo.lastName);
        $("#billaddr1").text(orderData.billTo.address1);
        $("#billaddr2").text(orderData.billTo.address2);
        $("#billcity").text(orderData.billTo.city);
        $("#billstate").text(orderData.billTo.state);
        $("#billzip").text(orderData.billTo.zip);
        $("#billcountry").text(orderData.billTo.country);

        $("#shiptofirstname").text(orderData.shipTo.firstName);
        $("#shiptolastname").text(orderData.shipTo.lastName);
        $("#shipaddr1").text(orderData.shipTo.address1);
        $("#shipaddr2").text(orderData.shipTo.address2);
        $("#shipcity").text(orderData.shipTo.city);
        $("#shipstate").text(orderData.shipTo.state);
        $("#shipzip").text(orderData.shipTo.zip);
        $("#shipcountry").text(orderData.shipTo.country);
    },

    submitOrder: function() {
        // 从 localStorage 获取订单数据
        const orderData = JSON.parse(localStorage.getItem('pendingOrder'));
        
        // 调用创建订单接口
        _order_service.createOrder(
            orderData,
            function(resp) {
                if (resp.status === 0) {
                    // 清除localStorage中的临时订单数据
                    localStorage.removeItem('pendingOrder');
                    // // 跳转到成功页面
                    // window.location.href = './order-success.html';
                     // 先显示成功提示
                alert('订单提交成功！');
                // 然后跳转到主界面
                window.location.href = './catalog-main.html';
                } else {
                    alert(resp.msg || '订单提交失败');
                }
            },
            function(errMsg) {
                alert(errMsg || '请求失败');
            }
        );
    }
};

module.exports = confirmOrder.init();